package com.wffz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wffz.comm.utils.*;
import com.wffz.dto.MoneyDTO;
import com.wffz.mapper.ClientUserMapper;
import com.wffz.mapper.MoneyLogMapper;
import com.wffz.po.*;
import com.wffz.service.*;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author sunlei
 * @className MoneyServiceImpl
 * @Description
 * @date 2023-02-05 11:35
 **/
@Service
@Slf4j
public class MoneyServiceImpl implements MoneyService {

    @Resource
    private UserService userService;

    @Resource
    private MoneyLogMapper logMapper;


    @Resource
    private IncomeLogService incomeLogService;

    @Resource
    private RechargeOrderService rechargeOrderService;

    @Resource
    private MoneyLogService moneyLogService;

    @Resource
    private CollectMoneyService collectMoneyService;

    @Resource
    private WffzConfigService configService;

    @Override
    @Transactional
    public String recharge(ClientUser user, MoneyDTO moneyDTO) {
        // 调用API接口
        // 充值金额
        Float balance = user.getBalance() == null ? 0 : user.getBalance();
        // 充值后金额
        Float newBalance = balance + moneyDTO.getMoney();
        // 新增订单
        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setLoginName(user.getLoginName());
        rechargeOrder.setUserId(user.getId());
        rechargeOrder.setAmount(moneyDTO.getMoney());
        rechargeOrder.setExtra(moneyDTO.getExtra());
        rechargeOrder.setCreateTime(new Date());
        rechargeOrder.setOrderStatus("0"); // 待支付状态
        boolean flag = rechargeOrderService.saveRechargeOrder(rechargeOrder);
        //
        String payUrl = null;
        if (flag) {
            // 调用支付接口
//            payUrl = payWeb(String.valueOf(moneyDTO.getMoney()), rechargeOrder.getId());
            String payResult = spayRecharge(moneyDTO.getMoney(), rechargeOrder.getId());
            JSONObject jobj = JSONObject.parseObject(payResult);
            int code = jobj.getIntValue("code");
            String data = jobj.getString("data");
            if (code == 1) {
                payUrl = data;
            }
//            // 判断是否是第一次充值，如果是第一次  加10元
//            int count = moneyLogService.moneyCount(user);
//            if(count<=0){
//                newBalance += 10 ;
//                IncomeLog incomeLog = new IncomeLog();
//                incomeLog.setAmount(10f);
//                incomeLog.setIncomeType("5");
//                incomeLog.setUserId(user.getId());
//                incomeLogService.saveInComeLog(incomeLog);
//            }else if (count==1){
//                newBalance += 10 ;
//                IncomeLog incomeLog = new IncomeLog();
//                incomeLog.setAmount(10f);
//                incomeLog.setIncomeType("6");
//                incomeLog.setUserId(user.getId());
//                incomeLogService.saveInComeLog(incomeLog);
//            }
//
//            // 日志
//            // 新增充值记录
//            MoneyLog moneyLog = new MoneyLog();
//            moneyLog.setLoginName(user.getLoginName());
//            moneyLog.setUserId(user.getId());
//            moneyLog.setMoney(moneyDTO.getMoney());
//            moneyLog.setBalanceBefore(balance);
//            moneyLog.setBalance(newBalance);
//            moneyLog.setCreateTime(new Date());
//            logMapper.insert(moneyLog);
//            //
//            IncomeLog in = new IncomeLog();
//            in.setAmount(balance);
//            in.setIncomeType("8");
//            in.setUserId(user.getId());
//            incomeLogService.saveInComeLog(in);
//            // 获取总计充值数额 设置VIP级别
//            Float moneyAll = moneyLogService.sumMoney(user);
//            if (moneyAll >= 200 && moneyAll <= 400) {
//                user.setVipLevel(1);
//            } else if (moneyAll > 400 && moneyAll <= 1000) {
//                user.setVipLevel(2);
//            } else if (moneyAll > 1000 && moneyAll <= 2000) {
//                user.setVipLevel(3);
//            } else if (moneyAll > 2000 && moneyAll <= 10000) {
//                user.setVipLevel(4);
//            } else if (moneyAll > 10000 && moneyAll <= 20000) {
//                user.setVipLevel(5);
//            } else if (moneyAll > 20000 && moneyAll <= 50000) {
//                user.setVipLevel(6);
//            } else if (moneyAll > 50000 && moneyAll <= 100000) {
//                user.setVipLevel(7);
//            } else if (moneyAll > 100000) {
//                user.setVipLevel(8);
//            }
//            //
//            user.setBalance(newBalance);
//            user.setAwayBalance(user.getAwayBalance() + rechargeOrder.getExtra());
//            userService.updateClientUser(user);
//            if (user.getAwayBalance()!=null && user.getAwayBalance()>0){
//                IncomeLog incomeLog = new IncomeLog();
//                incomeLog.setAmount(10f);
//                incomeLog.setIncomeType("8");
//                incomeLog.setUserId(user.getId());
//                incomeLogService.saveInComeLog(incomeLog);
//            }
        }

        return payUrl;
    }

    @Resource
    private RestTemplateUtil restTemplateUtil;

    /**
     * spay代收
     */
    public String spayRecharge(float tradeAmount, long rechagreId) {
        WffzConfig config = configService.getConfigByKey("pay_key");
        WffzConfig mchIdConfig = configService.getConfigByKey("mch_id");
        String merchant_key = config.getConfigKey();
        String url = "https://spayin.com/api/payment/recharge";
        JSONObject params = new JSONObject();
        params.put("callbackUrl", "http://172.104.206.64:9090/moneyBack/spayRechargeCallBack");
        params.put("merchantId", mchIdConfig.getConfigValue());
        params.put("merchantOrderId", String.valueOf(rechagreId));
        params.put("orderAmount", tradeAmount);
        params.put("timeMillis", System.currentTimeMillis());
        String signInfo = SignUtil.sortData(params);
        String sign = SignAPI.spaySign(signInfo, merchant_key); // 签名   signInfo签名参数排序，  merchant_key商户私钥
        params.put("sign", sign);
        System.out.println("请求参数：" + params.toString());
        String result = restTemplateUtil.httpPost(url, params);
        System.out.println("签名参数排序：" + signInfo.length() + " --> " + signInfo);
        System.out.println("sign值：" + sign.length() + " --> " + sign);
        System.out.println("result值：" + result);
        return result;
    }


    /**
     * @Description: [调用支付接口]
     * @Title: payWeb
     * @Author: SUNLEI
     * @Date: 2023-04-23
     * @Param: tradeAmount
     * @Param: rechagreId
     * @Return: java.lang.String
     * @Throws:
     */
    public String payWeb(String tradeAmount, long rechagreId) {
        String key = "pay_key";
        WffzConfig config = configService.getConfigByKey(key);
        WffzConfig mchIdConfig = configService.getConfigByKey("mch_id");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String url = "https://payment.allapay.com/pay/web";
        Map<String, String> params = new TreeMap<String, String>();
        params.put("version", "1.0");
        params.put("goods_name", "hello");
        params.put("mch_id", mchIdConfig.getConfigValue());
        params.put("mch_order_no", String.valueOf(rechagreId));
        params.put("notify_url", "http://172.104.206.64:9090/moneyBack/rechargeCallBack");
        params.put("order_date", sdf.format(new Date()));
        params.put("pay_type", "105");
        params.put("trade_amount", tradeAmount);
        String merchant_key = config.getConfigKey();
        String signInfo = SignUtil.sortData(params);
        String sign = SignAPI.sign(signInfo, merchant_key); // 签名   signInfo签名参数排序，  merchant_key商户私钥
        params.put("sign", sign);
        params.put("sign_type", "MD5");//不参与签名
        System.out.println(String.valueOf(rechagreId));
        System.out.println("请求参数：" + params.toString());
        String result = HttpClientUtil.doPost(url, params, "utf-8");
        System.out.println("签名参数排序：" + signInfo.length() + " --> " + signInfo);
        System.out.println("sign值：" + sign.length() + " --> " + sign);
        System.out.println("result值：" + result);
        JSONObject jobj = JSONObject.parseObject(result);
        String respCode = jobj.getString("respCode");
        String payUrl = null;
        if (respCode.equals("SUCCESS")) {
            payUrl = jobj.getString("payInfo");
        }
        return payUrl;
    }

    /**
     * @Description: [调用支付]
     * @Title: df
     * @Author: SUNLEI
     * @Date: 2023-02-28
     * @Param: amount
     * @Return: boolean
     * @Throws:
     */
    public boolean df(String amount) {
        boolean flag = false;
        CollectMoney money = collectMoneyService.getCollectMoneyDefault();
        if (money == null) {
            return false;
        }
        String dfUrl = "https://payment.weglobalpayment.com/pay/transfer";
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> forms = new LinkedMultiValueMap<String, String>();
        forms.put("sign_type", Collections.singletonList(money.getSignType()));
        forms.put("sign", Collections.singletonList(money.getSign()));
        forms.put("mch_id", Collections.singletonList(money.getMchId()));
        forms.put("mch_transferId", Collections.singletonList(UUID.randomUUID().toString()));
        forms.put("transfer_amount", Collections.singletonList(amount)); // 转账金额
        forms.put("apply_date", Collections.singletonList(DateUtils.dateTimeNow("yyyy-MM-dd hh:mm:ss"))); // 申请时间 时间格式：yyyy-MM-dd HH:mm:ss
        forms.put("bank_code", Collections.singletonList(money.getBankCode())); // 收款银行代码 填写固定值：IDPT0001
        forms.put("receive_name", Collections.singletonList(money.getReceiveName())); // 收款银行户名
        forms.put("receive_account", Collections.singletonList(money.getReceiveAccount())); // 收款银行账号 银行账号
        forms.put("remark", Collections.singletonList(money.getRemark())); // IFSC号码	印度银行分行编码，格式：ABCD0123456
        forms.put("back_url", Collections.singletonList(money.getBackUrl())); // 异步通知地址
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<MultiValueMap<String, String>>(forms, headers);
        //获取返回数据
        String body = restTemplate.postForObject(dfUrl, httpEntity, String.class);
        JSONObject jobj = JSONObject.parseObject(body);
        log.info("body" + body);
        String respCode = jobj.getString("respCode");
        log.info(jobj.getString("respCode"));
        if (respCode.equals("FAIL")) {
            String errorMsg = jobj.getString("errorMsg");
            log.info("transfer is error , errorMsg :" + errorMsg);
            flag = false;
        } else if (respCode.equals("SUCCESS")) {
            flag = true;
        }
        return flag;
    }

    @Override
    public List<MoneyLog> getMoneyLogTop3() {
        QueryWrapper<MoneyLog> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time").last(" limit 3");
        List<MoneyLog> list = logMapper.selectList(wrapper);
        return list;
    }

    @Override
    public PageInfo<MoneyLog> queryMoneyLog(Integer pageNum, Integer pageSize, String loginName) {
        PageHelper.startPage(pageNum, pageSize);
        QueryWrapper<MoneyLog> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", loginName);
        wrapper.orderByDesc("create_time");
        List<MoneyLog> moneyLogs = logMapper.selectList(wrapper);
        PageInfo<MoneyLog> pageInfo = new PageInfo<>(moneyLogs);
        return pageInfo;
    }
}
